package ruifeng.zcj.communcationring.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rey.material.widget.SnackBar;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import ruifeng.zcj.communcationring.base.utils.TUtil;

/**
 * Created by Administrator on 2016/8/16 0016.
 * 切换到该Fragment

 11-29 14:26:35.095: D/AppListFragment(7649): onAttach
 11-29 14:26:35.095: D/AppListFragment(7649): onCreate
 11-29 14:26:35.095: D/AppListFragment(7649): onCreateView
 11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated
 11-29 14:26:35.120: D/AppListFragment(7649): onStart
 11-29 14:26:35.120: D/AppListFragment(7649): onResume
 屏幕灭掉：

 11-29 14:27:35.185: D/AppListFragment(7649): onPause
 11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState
 11-29 14:27:35.205: D/AppListFragment(7649): onStop

 屏幕解锁

 11-29 14:33:13.240: D/AppListFragment(7649): onStart
 11-29 14:33:13.275: D/AppListFragment(7649): onResume

 切换到其他Fragment:
 11-29 14:33:33.655: D/AppListFragment(7649): onPause
 11-29 14:33:33.655: D/AppListFragment(7649): onStop
 11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView

 切换回本身的Fragment:

 11-29 14:33:55.820: D/AppListFragment(7649): onCreateView
 11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated
 11-29 14:33:55.825: D/AppListFragment(7649): onStart
 11-29 14:33:55.825: D/AppListFragment(7649): onResume
 回到桌面

 11-29 14:34:26.590: D/AppListFragment(7649): onPause
 11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState
 11-29 14:34:26.880: D/AppListFragment(7649): onStop
 回到应用

 11-29 14:36:51.940: D/AppListFragment(7649): onStart
 11-29 14:36:51.940: D/AppListFragment(7649): onResume


 退出应用

 11-29 14:37:03.020: D/AppListFragment(7649): onPause
 11-29 14:37:03.155: D/AppListFragment(7649): onStop
 11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView
 11-29 14:37:03.165: D/AppListFragment(7649): onDestroy
 11-29 14:37:03.165: D/AppListFragment(7649): onDetach
 */
public abstract class BaseFragment<T extends BasePresenter,E extends BaseModel> extends Fragment{
    private static final String TAG = "BaseFragment";
    private BaseActivity baseActivity;
    private boolean isPrepared;
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isCallSetUserVisibleHint = false;
    public T mPresenter;
    public E mModel;
    protected BaseActivity mActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (this instanceof BaseView) mPresenter.setVM(this, mModel);

        return inflater.inflate(getContentView(), container, false);
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (BaseActivity) activity;
        //TAG = this.getClass().getSimpleName();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getActivity() instanceof BaseActivity) {
            baseActivity = (BaseActivity) getActivity();
        }
        ButterKnife.bind(this, view);

        initFragmentConfig();// 初始化的工作
    }

    /**
     * here we can do some initialized work
     */
    protected abstract void initFragmentConfig();

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();// 加载数据
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        cleanMemory();
        if (mPresenter != null) mPresenter.onDestroy();
    }


    @Override
    public void onDetach() {
        super.onDetach();
        // for bug ---> java.lang.IllegalStateException: Activity has been destroyed
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }



    /***
     * 切换到该Fragment
     11-29 14:26:35.095: D/AppListFragment(7649): onAttach
     11-29 14:26:35.095: D/AppListFragment(7649): onCreate
     11-29 14:26:35.095: D/AppListFragment(7649): onCreateView
     11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated
     11-29 14:26:35.120: D/AppListFragment(7649): onStart
     11-29 14:26:35.120: D/AppListFragment(7649): onResume
     * **/
    @Override
    public void onResume() {
        super.onResume();
        if (isFirstResume && isCallSetUserVisibleHint) {
            isFirstResume = false;
            return;
        }
        if (getUserVisibleHint()) {// 判断当前的Fragment是否是在显示
            onUserVisible();
        }
    }

    /****
     * 屏幕灭掉：
     11-29 14:27:35.185: D/AppListFragment(7649): onPause
     11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState
     11-29 14:27:35.205: D/AppListFragment(7649): onStop
     切换到其他Fragment:
     11-29 14:33:33.655: D/AppListFragment(7649): onPause
     11-29 14:33:33.655: D/AppListFragment(7649): onStop
     11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView
     * **/
    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {// true看的见
            onUserInvisible();
        }
    }

    @Override
    public boolean getUserVisibleHint() {
        return super.getUserVisibleHint();
    }

    /****
     * 判断是否显示当前Fragment显示为true否则为false
     * **/
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCallSetUserVisibleHint = true;

        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
                onFirstUserInvisible();
            } else {
                onUserInvisible();
            }
        }
    }

    protected synchronized void initPrepare() {
        if (isPrepared || !isCallSetUserVisibleHint) {
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }
    protected abstract int getContentView();

    /**
     * 只运行一次，当fragment可见的时候
     * when fragment is visible for the first time,  refresh data only once
     */
    protected abstract void onFirstUserVisible();

    /**
     * when fragment is invisible for the first time
     */
    protected void onFirstUserInvisible() {
        Log.d(TAG, "onFirstUserInvisible() called with: " + "");
        // here we do not recommend do something
    }

    /**
     * this method like the fragment's lifecycle method onResume()
     */
    protected abstract void onUserVisible();

    /**
     * this method like the fragment's lifecycle method onPause()
     */
    protected abstract void onUserInvisible();
    /**
     * 清除内存
     * **/
    protected abstract void cleanMemory();


    public void showSnackBar(String message){
        SnackBar.make(App.getAppContext()).actionText(message).duration(Snackbar.LENGTH_SHORT).show();
    }

    public BaseActivity getBaseActivity() {
        return baseActivity;
    }




    protected void showLoadingDialog(String titleText) {
        mActivity.showLoadingDialog("" + titleText);
    }

    protected void dismissLoadingDialog() {
        if (isVisible()) {
            mActivity.dismissLoadingDialog();
        }
    }

}
